<template>
	<div class="thread-manager">
		<div class="main_content">
			<div class="main_content_title">
				<div class="left">
					<template v-for="(item, index) in $route.meta.title">
						<span v-if="languageId === item.langId">{{ item.name }}</span>
					</template>
				</div>
				<div class="right">
					<template v-for="(btn, index) in buttonList">
						<el-button v-if="btn.perms === 'A'" :key="index + new Date()" type="primary" size="mini" @click="addData">
							<template v-for="(title, index_1) in btn.title">
								<span v-if="languageId === title.langId">{{ title.name }}</span>
							</template>
						</el-button>
						<el-button v-if="btn.perms === 'F'" :key="index + new Date()" type="warning" size="mini"
							@click="getAllocation">
							<template v-for="(title, index_1) in btn.title">
								<span v-if="languageId === title.langId">{{ title.name }}</span>
							</template></el-button>
					</template>
				</div>
			</div>
			<div class="main_content_con">
				<el-table ref="qtable" v-loading="tableLoading || tableConfigLoading" :data="tableList" tooltip-effect="dark"
					row-key="id" :tree-props="{ children: 'children' }" :default-expand-all="false" :select-on-indeterminate="true"
					:border="true" height="100%" @row-click="tableCurrentChange" @selection-change="tableSelectionChange"
					@header-dragend="tableHeaderDragend">
					<!-- <el-table-column key="index" type="index" :resizable="false" width="50" fixed="left" align="center" /> -->
					<el-table-column key="selection" type="selection" :resizable="false" width="50" fixed="left" align="center"
						:selectable="setDisabled" />
					<template v-for="(item, headerIndex) in tableConfig">
						<el-table-column
							v-if="item.show && (branchId ? (item.key !== 'branchName' && item.key !== 'companyName') : (!branchId && companyId) ? item.key !== 'companyName' : item.key)"
							:key="item.key" :column-key="item.key" :min-width="item.width" :show-overflow-tooltip="true"
							:resizable="item.resizable" :fixed="item.fixed" align="center">
							<template slot="header" slot-scope="scope">
								<div class="header_item" v-if="!item.keySort" style="cursor: default;">
									{{ item.label }}
								</div>
								<div class="header_item" v-if="item.keySort"
									@click.stop="getkeySort(item.key, item.keySort, field !== item.keySort ? 0 : order === 0 && keySortFlag ? 1 : order === 1 && keySortFlag ? -1 : 0)">
									{{ item.label }}
									<div class="keySort">
										<i class="el-icon-caret-top" :style="{ color: keySortValue == item.key ? topIconColor : '#c0c4cc' }"
											@click.stop="getkeySort(item.key, item.keySort, 0)" />
										<i class="el-icon-caret-bottom"
											:style="{ color: keySortValue == item.key ? bottomIconColor : '#c0c4cc' }"
											@click.stop="getkeySort(item.key, item.keySort, 1)" />
									</div>
								</div>
								<div v-if="showSearch" class="search_box">
									<div v-if="item.searchEnable">
										<div v-if="item.searchType === 'select'" class="select_box"
											:class="[item.key ? 'input_key_' + item.key : '']">
											<el-select v-model="item.value" :placeholder="$t('placeholderTip.pSelect')" size="mini" clearable
												filterable @change="getList">
												<el-option v-for="(option, optionIndex) in item.options"
													:key="item.key + '_select_' + optionIndex" :label="option.label" :value="option.value" />
											</el-select>
										</div>
										<div v-else-if="item.searchType === 'timeRange'" class="time_range_box">
											<el-date-picker v-model="item.value" type="daterange" align="right" size="mini" unlink-panels
												:range-separator="$t('text.to')" :start-placeholder="$t('el.datepicker.startTime')"
												:end-placeholder="$t('el.datepicker.endTime')" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
												@change="getList" />
										</div>
										<div v-else class="input_box">
											<el-input v-model="item.value" size="mini" clearable :placeholder="$t('placeholderTip.enter')"
												:tabindex="headerIndex + 1 + ''" @keyup.enter.native="getList" @clear="getList" />
										</div>
									</div>
								</div>
							</template>
							<template slot-scope="scope">
								<span v-if="item.key === 'sex'">{{ scope.row[item.key] === 1 ? $t('text.male') : $t('text.female')
								}}</span>
								<span v-else>{{ scope.row[item.key] || '-' }}</span>
							</template>
						</el-table-column>
					</template>
					<el-table-column key="setting" width="90" :resizable="false" fixed="right" align="center">
						<template slot="header">
							<div style="display: flex;align-items: center;justify-content: center;">
								<el-button type="text" @click.stop="openSearchView">
									<svg-icon icon-class="filter" />
								</el-button>
								<span style="display: inline-block;width: 1px;height: 20px;background-color: #c2c2c2;margin: 0 10px;" />
								<el-button type="text" class="el-icon-setting" @click.stop="showTableConfigDialog = true" />
							</div>
							<div v-if="showSearch" class="search_box">
								<el-button type="text" icon="el-icon-search" style="width: 50%" circle @click.stop="getList" />
								<el-button type="text" icon="el-icon-circle-close" style="width: 50%; margin-left: unset" circle
									@click.stop="cleanSearch" />
							</div>
						</template>
						<template slot-scope="scope">
							<div @click.stop>
								<el-dropdown trigger="click" @command="handleCommand($event, scope.row)">
									<span class="el-dropdown-link">
										<img src="@/assets/images/menu_more.svg">
									</span>
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item command="detail">{{ $t('publicBtn.detail') }}</el-dropdown-item>
										<template v-for="(btn, index) in buttonList">
											<span :key="index + new Date()">
												<el-dropdown-item v-if="btn.perms === 'F' && scope.row['clueStatus'] === 0" command="allocate">
													<template v-for="title in btn.title">
														<span v-if="languageId === title.langId">{{ title.name }}</span>
													</template>
												</el-dropdown-item>
												<el-dropdown-item v-if="btn.perms === 'U' && scope.row['clueStatus'] === 0" command="edit">
													<template v-for="title in btn.title">
														<span v-if="languageId === title.langId">{{ title.name }}</span>
													</template>
												</el-dropdown-item>
											</span>
										</template>
									</el-dropdown-menu>
								</el-dropdown>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="pagination_box">
				<el-pagination :current-page="pagination.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="pagination.limit"
					layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 设置表头 -->
		<table-config-dialog :visible="showTableConfigDialog" :table-config="tableConfig" @change="tableConfigChange"
			@close="closeTableConfigDialog" />

		<!-- 线索模块 -->
		<el-dialog
			:title="propUpType === 'add' ? $t('text.addClue') : propUpType === 'edit' ? $t('text.editClue') : $t('text.detail')"
			width="50%" :visible.sync="addDialogVisible" append-to-body custom-class="add_dialog">
			<el-form ref="info" :model="info" :rules="rules" label-width="100px" class="demo-ruleForm">
				<el-form-item :label="$t('publicFormLabel.name')" prop="name">
					<el-input v-model="info.name" :placeholder="$t('placeholderTip.enter')" />
				</el-form-item>
				<el-form-item :label="$t('publicFormLabel.phone')" prop="phone">
					<el-input v-model="info.phone" type="number" @mousewheel.native.prevent @keydown.native.up.prevent
						@keydown.native.down.prevent @keydown.native.tab.prevent :placeholder="$t('placeholderTip.enter')" />
				</el-form-item>
				<el-form-item :label="$t('formLabel.sex')" prop="sex">
					<el-radio-group :value="info.sex" v-model="info.sex">
						<el-radio :label=1>{{ $t('text.male') }}</el-radio>
						<el-radio :label=2>{{ $t('text.female') }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item :label="$t('formLabel.intendedVehicle')" prop="intendedId">
					<el-select v-model="info.intendedId" filterable clearable :placeholder="$t('placeholderTip.pSelect')"
						style="width:99%">
						<el-option v-for="item in interestedModelsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('publicFormLabel.channelStatus')" prop="projectId">
					<el-select v-model="info.projectId" filterable clearable :placeholder="$t('placeholderTip.pSelect')"
						style="width:99%">
						<el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('publicFormLabel.describe')" prop="remark">
					<el-input v-model="info.remark" type="textarea" :placeholder="$t('placeholderTip.enter')" />
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">{{ propUpType === 'detail' ? $t('el.popconfirm.close') :
					$t('el.popconfirm.cancelButtonText') }}</el-button>
				<el-button v-if="propUpType !== 'detail'" type="primary" @click="addSubmitForm"
					v-loading.fullscreen.lock="fullscreenLoading">{{ $t('el.popconfirm.confirmButtonText') }}</el-button>
			</span>
		</el-dialog>

		<!-- 分配 -->
		<allocation ref="allocation"></allocation>

	</div>
</template>
<script>
import {
	getClueList,
	setClueSave
} from '@/api/client'
import { getPresaleAttributeList } from '@/api/public'
import { getTableHeaderList } from '@/api/table-config'
import allocation from '@/components/allocation'
import tableConfigDialog from '@/components/table-config-dialog'
import UploadImgSimple from '@/components/Upload/UploadImgSimple'
import { getToken } from '@/utils/auth'
export default {
	name: 'ThreadManager',
	components: {
		tableConfigDialog,
		UploadImg: UploadImgSimple,
		allocation,
	},
	data() {
		return {
			pagination: {
				page: 1,
				limit: 20,
				total: 0
			},
			branchId: this.$store.getters.branchId, //是否是门店
			companyId: this.$store.getters.companyId, //是否公司
			isDescribe: this.$store.getters.isDescribe, //DCC描述 1开启 2关闭
			tableSelectedList: [],
			showTableConfigDialog: false,
			refreshDelay: 200,
			tableLoading: false,
			showSearch: false,
			tableConfigLoading: false,
			tableConfig: [],
			keySortValue: '',
			topIconColor: '#c0c4cc',
			bottomIconColor: '#c0c4cc',
			tableList: [],
			field: '', // 排序字段
			keySortFlag: true,
			order: '', // 类型  0:正序 1:倒序
			buttonList: [], // 按钮
			propUpType: '', // 弹出状态  add  edit
			addDialogVisible: false,
			info: {
				name: null, //名称
				phone: '', //电话
				sex: 1,
				intendedModel: '', //意向车型
				intendedId: '', //意向车型Id
				projectId: '', //渠道状态
				remark: '' // 描述
			},
			projectList: [], //渠道状态
			interestedModelsList: [], //意向车型list
			rules: {
				name: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				phone: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
					// {
					// 	required: true,
					// 	// pattern:/^1(3|4|5|6|7|8|9)\d{9}|(0[0-9]{2,3})([2-9][0-9]{4,7})+([0-9]{1,4})$/, 电话 1开头-11位  固化 必须0开头区
					// 	pattern: '\\d{11,12}', //校验长度 11位或者12位
					// 	message: '请输入正确的电话号码',
					// 	trigger: 'blur'
					// }
				],
				name: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				// remark: [
				//   {
				//     required: true,
				// message: this.$t('placeholderTip.enter'),
				//     trigger: 'blur'
				//   }
				// ],
				projectId: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				]
			},
			invalidRemark: '', //无效描述
			token: getToken(),
			fullscreenLoading: false
		}
	},
	watch: {
		tableConfig: {
			handler(val) {
				this.pagination.page = 1
			},
			deep: true
		}
	},
	computed: {
		languageId() {
			// 固定语种ID  1:中文  2:英文 3:俄文 4:乌语
			return this.$store.getters.languageId
		}
	},
	mounted() {
		window._vm = this
		this.buttonList = this.$route.meta.buttonList
		this.bindEvent()
		this.initTableHeader()
	},
	created() {
		console.log('created ')
	},
	activated() {
		console.log('activated')
	},
	destroyed() {
		this.removeEvent()
	},
	methods: {
		getAllocation() {
			var list = this.tableSelectedList
			if (list.length < 1) {
				this.$message({
					message: this.$t('text.pSelLeastList'),
					type: 'warning'
				})
				return
			}
			var newIds = []
			for (var i = 0; i < list.length; i++) {
				newIds.push(list[i].id)
			}
			var ids = newIds.toString()
			this.$refs.allocation.getOpen(ids)
		},

		// 渠道状态 //意向车型
		getPresaleAttributeListData(ids) {
			getPresaleAttributeList(ids).then(res => {
				if (res.code === 200) {
					if (ids === 1) {
						this.projectList = res.data.projectId
					} else if (ids === 7) {
						this.interestedModelsList = res.data.intendedList
					}
				}
			})
		},

		// 排序功能
		getkeySort(key, keySort, order) {
			var obj = {
				key: key, //当前key 值
				keySort: keySort, //筛选key值
				order: order, //当前类型 0:正序 1:倒序
				this_keySortValue: this.keySortValue, //当前的筛选key值
				this_topIconColor: this.topIconColor, //定义 正序值
				this_bottomIconColor: this.bottomIconColor, // 倒序值
				this_order: this.order, //定义的类型 0:正序 1:倒序
				this_keySortFlag: this.keySortFlag //data定义 的 keySortFlag
			}
			let data = this.SortData(obj) //调起方法并传值   data 方法返回的值
			if (data) {
				this.keySortValue = data.keySortValue
				this.topIconColor = data.topIconColor
				this.bottomIconColor = data.bottomIconColor
				this.order = data.order
				this.keySortFlag = data.keySortFlag
				this.field = data.field
				this.getList()
			}
		},
		removeEvent() {
			window.removeEventListener('resize', this.refresh)
		},
		bindEvent() {
			window.addEventListener('resize', this.refresh)
		},
		tableSelectionChange(selection) {
			this.tableSelectedList = selection
		},
		// table 表格复选框禁用
		setDisabled(row, index) {
			// 已分配   未回访 禁选
			//  DCC描述 1描述必填 2 非必填
			// clueStatus 1已分配  0  待分配
			if (Number(this.isDescribe) === 1) {
				if (row.clueStatus === 1 || !row.remark) {
					return false
				} else {
					// 已回访 待分配可选
					return true
				}
			} else {
				if (row.clueStatus === 1) {
					return false
				} else {
					// 已回访 待分配可选
					return true
				}
			}
		},
		// 关闭弹框
		closeTableConfigDialog() {
			this.showTableConfigDialog = false
		},
		tableHeaderDragend(newWidth, oldWidth, column, event) {
			var tar = this.tableConfig.find(item => item.key === column.columnKey)
			this.$nextTick(() => {
				if (tar) {
					if (newWidth < 130) {
						column.width = 130
						tar.width = 130
					} else {
						tar.width = newWidth
					}
				}
			})
		},
		tableCurrentChange(row) {
			// console.log(row, 'row');
			if (Number(this.isDescribe) === 1) {
				// DCC描述必填
				if (row.clueStatus === 0 && row.remark) {
					this.$refs['qtable'].toggleRowSelection(row)
				}
			} else {
				// DCC描述不必填
				if (row.clueStatus === 0) {
					this.$refs['qtable'].toggleRowSelection(row)
				}
			}
		},
		cleanSearch() {
			var tag = false
			this.tableConfig.forEach(item => {
				if (item.searchEnable) {
					if (typeof item.value !== 'undefined') {
						if (item.value !== '') {
							item.value = ''
							tag = true
						}
					}
				}
			})
			tag && this.getList()
		},
		openSearchView() {
			this.showSearch = !this.showSearch
			setTimeout(() => {
				this.refresh()
			}, 200)
		},

		refresh() {
			try {
				setTimeout(() => {
					if (this.$refs['qtable']) {
						this.$refs.qtable.doLayout()
						this.$refs.qtable.bodyWrapper.scrollTop = 0
					}
				}, this.refreshDelay)
			} catch (error) {
				//
			}
		},
		// 表头
		tableConfigChange(tableConfig) {
			if (tableConfig) {
				this.tableConfig = tableConfig
			} else {
				this.initTableHeader()
			}
		},

		// 表头接口
		initTableHeader() {
			var menuId = this.$route.meta.id
			getTableHeaderList(menuId).then(res => {
				if (res.code === 200) {
					this.tableConfig = this.checkTableHeader(JSON.parse(res.data))
					this.tableSelectedList = []
					this.getList()
				}
			})
		},
		checkTableHeader(list) {
			list.forEach(item => {
				if (item.searchEnable) {
					if (item.searchType === 'select') {
						if (
							Object.prototype.toString.call(item.options) === '[object Array]'
						) {
							if (item.options.length) {
								item.optionsForAdd = JSON.parse(JSON.stringify(item.options))
							}
						}
					}
					if (typeof item.value === 'undefined') {
						this.$set(item, 'value', '')
					}
				}
			})
			return list
		},
		// 列表接口
		getList() {
			this.tableLoading = true
			var params = {
				page: this.pagination.page,
				limit: this.pagination.limit,
				field: this.field,
				order: this.order
			}
			this.tableConfig.forEach(item => {
				if (item.searchEnable && item.value) {
					console.log('key : ' + item.key + '\n' + 'value : ' + item.value)
					if (item.searchType === 'timeRange') {
						params[item.searchField || item.key] = item.value.join(',')
					} else {
						params[item.searchField || item.key] = item.value
					}
				}
			})
			var searchObj = ''
			// // 筛选条件取值
			if (Object.keys(params).length > 0) {
				Object.keys(params).forEach(function (key, index) {
					if (index === 0) {
						// 第一个 不需要  '&'
						searchObj = searchObj.concat(`${key}=${params[key]}`)
					} else {
						searchObj = searchObj.concat('&' + `${key}=${params[key]}`)
					}
				})
			}
			getClueList(searchObj)
				.then(res => {
					if (res.code === 200) {
						this.tableList = res.data.list
						this.pagination.limit = res.data.pageSize
						this.pagination.total = res.data.totalCount
						this.refresh()
					}
				})
				.finally(() => {
					this.tableLoading = false
				})
		},
		// 添加数据
		addData() {
			this.resetForm('info')
			this.info = {
				name: '', //名称
				phone: '', //电话
				sex: 1,
				intendedModel: '', //意向车型
				intendedId: '', //意向车型Id
				projectId: '', //渠道状态
				remark: '' // 描述
			}
			this.propUpType = 'add'
			this.addDialogVisible = true
			this.getPresaleAttributeListData(7)
			this.getPresaleAttributeListData(1)
		},

		handleCommand(val, tar) {
			switch (val) {
				case 'edit':
					this.$router.push({
						path: '/thread-manager-info',
						query: { propUpType: 'edit', id: tar.id }
					})
					break
				case 'allocate':
					if (!tar.remark && Number(this.isDescribe) === 1) {
						this.$message({
							message: this.$t('text.allocationInfoTip'),
							type: 'warning'
						})
						return
					}
					this.$refs.allocation.getOpen(tar.id)
					break
				case 'detail':
					this.$router.push({
						path: '/thread-manager-info',
						query: { propUpType: 'detail', id: tar.id }
					})
					break
				default:
					break
			}
		},
		// 重置表单
		resetForm(vaid) {
			if (this.$refs[vaid] !== undefined) {
				this.$nextTick(() => {
					this.$refs[vaid].resetFields()
				})
			}
		},
		addSubmitForm() {
			this.$refs['info'].validate(valid => {
				if (valid) {
					var obj = this.info
					this.interestedModelsList.filter(item => {
						if (obj.intendedId === item.id) {
							obj.intendedModel = item.name
						}
					})
					var params = {
						name: obj.name, //名称
						phone: obj.phone, //电话
						sex: obj.sex,
						intendedModel: obj.intendedModel, //意向车型
						intendedId: obj.intendedId, //意向车型Id
						projectId: obj.projectId, //渠道状态
						remark: obj.remark // 描述
					}
					this.fullscreenLoading = true
					setClueSave(params)
						.then(res => {
							if (res.code === 200) {
								this.$message({
									showClose: true,
									message: '添加成功',
									type: 'success'
								})
								this.fullscreenLoading = false
								this.addDialogVisible = false
								this.getList()
							}
						})
						.catch(err => {
							this.fullscreenLoading = false
							console.log(err, 'err')
						})
				} else {
					return false
				}
			})
		},
		// 分页
		handleSizeChange(val) {
			this.pagination.limit = val
			this.getList()
		},
		handleCurrentChange(val) {
			this.pagination.page = val
			this.getList()
		}
	}
}
</script>
<style lang="scss" scoped>
.thread-manager {
	height: 100%;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;

	&>.main_content {
		width: 99.9%;
		height: 100%;

		&>.main_content_title {
			margin-bottom: 10px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		.main_content_con {
			height: calc(100% - 70px);
			width: 100%;
			display: inline-block;

			.el-table {
				::v-deep .el-icon-arrow-right {
					font-weight: 600;
				}

				::v-deep th {
					padding: unset;
					background-color: #f2f2f2;

					.header_item {
						height: 39px;
						line-height: 39px;
						display: flex;
						justify-content: center;
						align-items: center;
						cursor: pointer;

						&>.keySort {
							width: 23px;
							height: 21px;
							position: relative;
							display: inline-block;

							&>.el-icon-caret-top {
								position: absolute;
								top: 0;
								right: 0;
								left: 0;
								margin: auto;
								cursor: pointer;
							}

							&>.el-icon-caret-bottom {
								position: absolute;
								bottom: 0;
								right: 0;
								left: 0;
								margin: auto;
								cursor: pointer;
							}
						}
					}
				}

				.colorContnet {
					padding: 12px 10px;
					box-sizing: border-box;
					border-radius: 10px;
					color: #fff;
					font-size: 12px;
				}

				.el-dropdown {
					cursor: pointer;
				}
			}
		}
	}
}
</style>

<style lang="scss" scoped>
::v-deep .add_dialog {
	height: calc(100% - 30vh) !important;
	position: relative;

	.el-dialog__header {
		border-bottom: 1px solid #e4e4e4;
		text-align: left;
	}

	.el-dialog__body {
		height: calc(100% - 125px);
		overflow: auto;
	}

	.el-dialog__footer {
		border-top: 1px solid #e4e4e4;
		text-align: right;
	}

	.el-button:hover,
	.el-button:focus {
		color: #000;
	}

	.remark {
		height: auto;
		display: flex;
		justify-content: space-between;

		.title {
			width: 80px;
		}
	}
}
</style>

